﻿
Imports System.Runtime.CompilerServices
Imports System.Net
Imports osi.root.connector
Imports osi.root.procedure

Public Module _response
    <Extension()> Public Function write_response(ByVal ctx As HttpListenerContext,
                                                 ByVal content As String,
                                                 Optional ByVal e As Text.Encoding = Nothing) As event_comb
        Dim ec As event_comb = Nothing
        Return New event_comb(Function() As Boolean
                                  If ctx Is Nothing Then
                                      Return False
                                  ElseIf String.IsNullOrEmpty(content) Then
                                      ctx.Response().StatusCode() = HttpStatusCode.NoContent
                                      ctx.Response().StatusDescription() = "NO CONTENT"
                                      Return goto_end()
                                  Else
                                      If e Is Nothing Then
                                          e = default_encoding
                                      End If
                                      Dim b() As Byte = Nothing
                                      b = e.GetBytes(content)
                                      ec = ctx.Response().OutputStream().write(b)
                                      Return waitfor(ec) AndAlso
                                             goto_next()
                                  End If
                              End Function,
                              Function() As Boolean
                                  Return ec.end_result() AndAlso
                                         goto_end()
                              End Function)
    End Function
End Module
